package com.jinzecloud.reportapproval.controller;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

//import org.apache.shiro.authz.annotation.RequiresPermissions;
import com.alibaba.excel.EasyExcel;
import com.jinzecloud.reportapproval.dto.InstrumentExcel;
import com.jinzecloud.reportapproval.dto.TreeExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import com.jinzecloud.reportapproval.bean.Instrument;
import com.jinzecloud.reportapproval.service.InstrumentService;
import com.jinzecloud.reportapproval.utils.PageUtils;
import com.jinzecloud.reportapproval.utils.R;
import org.springframework.web.multipart.MultipartFile;


/**
 * 仪器表信息
 *
 * @author æ­å°
 * @email 1971240051@qq.com
 * @date 2024-12-03 16:18:45
 */
@RestController
@RequestMapping("reportapproval/instrument")
public class InstrumentController {
    @Autowired
    private InstrumentService instrumentService;

    @Value("${upload.path}")
    private String path;

    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("reportapproval:instrument:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = instrumentService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    //@RequiresPermissions("reportapproval:instrument:info")
    public R info(@PathVariable("id") Integer id){
		Instrument instrument = instrumentService.getById(id);

        return R.ok().put("instrument", instrument);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    //@RequiresPermissions("reportapproval:instrument:save")
    public R save(@RequestBody Instrument instrument){
		R r = instrumentService.saveInstrument(instrument);

        return r;
    }

    @RequestMapping("/getInstrument")
    public R getInstrument(){
        List<Instrument> instrumentList  = instrumentService.getInstrument();
    	return R.ok().put("instrumentList", instrumentList);
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("reportapproval:instrument:update")
    public R update(@RequestBody Instrument instrument){
		instrumentService.updateById(instrument);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("reportapproval:instrument:delete")
    public R delete(@RequestBody Integer[] ids){
		instrumentService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    @PostMapping(value = "/uploadFile")
    public R uploadFile(MultipartFile file){
        // 检查文件是否为空
        if (file.isEmpty()) {
            return  R.error(400,"上传失败，文件为空！");
        }
        try {

            List<InstrumentExcel> twoExcel = EasyExcel.read(file.getInputStream()).head(InstrumentExcel.class).sheet().headRowNumber(2).doReadSync();
            List<TreeExcel> treeExcels = EasyExcel.read(file.getInputStream()).head(TreeExcel.class).sheet().headRowNumber(3).doReadSync();
            // 去除从第二行读取的多余表头数据
            int removePosition = twoExcel.size() - treeExcels.size();
            for(int i = removePosition; i >= 1; i -- ){
                twoExcel.remove(0);
            }
            List<Instrument> instrumentList = new ArrayList<>();
            for (int i = 0; i < twoExcel.size(); i++) {
                Instrument instrument = new Instrument();
                instrument.setInstrumentName(twoExcel.get(i).getInstrumentName());
                instrument.setInstrumentNumber(twoExcel.get(i).getSelfNumber());
                instrument.setMeasuringRange(treeExcels.get(i).getRange());
                instrument.setAccuracyRating(treeExcels.get(i).getResolution());
                instrumentList.add(instrument);
            }

            // 去除重复元素
            List<Instrument> distinctInstrumentList = instrumentList.stream()
                    .collect(Collectors.toMap(Instrument::getInstrumentNumber, instrument -> instrument, (existing, replacement) -> existing))
                    .values()
                    .stream()
                    .collect(Collectors.toList());

            // 排除掉已存在数据库中的元素
            List<Instrument> list = instrumentService.list();
            Set<String> instrumentNumberSet = list.stream()
                    .map(Instrument::getInstrumentNumber)
                    .collect(Collectors.toSet());
            List<Instrument> filteredDistinctInstrumentList = distinctInstrumentList.stream()
                    .filter(instrument -> !instrumentNumberSet.contains(instrument.getInstrumentNumber()))
                    .collect(Collectors.toList());


            instrumentService.saveBatch(filteredDistinctInstrumentList);

            // 返回上传成功的响应
            return R.ok("上传成功");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.error();
    }
}
